<?php
/**
 *  * 系统-受国家计算机软件著作权保护 - !
 * =========================================================
 * Copy right 2018-2025 成都海之心科技有限公司, 保留所有权利。
 * ----------------------------------------------
 * 官方网址: http://www.ohyu.cn
 * 这不是一个自由软件！在未得到官方有效许可的前提下禁止对程序代码进行修改和使用。
 * 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
 * =========================================================
 * User: ohyueo
 * Date: 2021/5/17
 * Time: 10:49
 */

namespace app\admin\controller;
use think\facade\View;
use think\facade\Db;
use app\common\Qiniu;

class Tools extends Common
{
    public function __construct()
    {
        parent::initialize();
    }
    # 选择图片
    public function select_img()
    {
        if (request()->isPost()){
            $action = input('action');
            $page = input('page',1);
            $limit = input('limit',10);
            switch ($action){

                # 查询指定文件夹
                case 'fetch_folder':
                    # TODO 完善图片文件夹功能 #
                    return json(['code'=>200,'message'=>'成功','data'=>[]]);

                # 删除图片
                case 'delete':
                    $id = input('id');
                    if (is_array($id)){
                        $d = Db::name('ohyueo_img_list')->whereIn('id',$id);
                    }else{
                        $d = Db::name('ohyueo_img_list')->where('id',$id);
                    }
                    if ($d->count()){
                        try {
                            $d = $d->select()->toArray();
                            foreach ($d as $data){
                                $path = app()->getRootPath().'public'.$data['path'];
                                if ($data['site']){
                                    Qiniu::delete($data['path']);
                                }else{
                                    if (file_exists($path)) unlink($path);
                                }
                                Db::name('ohyueo_img_list')->where('id',$data['id'])->delete();
                            }
                            return Json::Success();
                        }catch (Exception $e){
                            return json(['code'=>-1,'message'=>$e->getMessage(),'data'=>[]]);
                        }
                    }else{
                        return json(['code'=>400,'message'=>'该图片不存在','data'=>[]]);
                    }

                # 查询图片列表
                default:
                    $d = Db::name('ohyueo_img_list')->where('state',1)->where('type',1);
                    $count = $d->count();
                    $data=$d->page($page,$limit)->select()->toArray();
                    return json(['code'=>200,'message'=>'成功','data'=>$data,'count'=>$count]);
            }
        }else return View::fetch();
    }

    public function upload(){
        $is = (bool)input('site',true);
        $res = $this->handel_upload([
            'fileSize' => config('-upload.img_size') ?? 3145728,
            'fileExt' => config('-upload.img_ext') ?? 'jpg,png,jpeg',
            'fileMime' => 'image/jpeg,image/png,image/gif',
        ],'admin_images',$is)->getData();
        if ($res['code'] === 0){
            if (input('new')){
                $arr = [
                    'path' => $res['filename'],
                ];
                if ($res['site']) $arr['site'] = getUrl();
                Db::name('ohyueo_img_list')->insertGetId($arr);
                $res['count'] = Db::name('ohyueo_img_list')->where('state',1)->where('type',1)->count();
                return $res;
            }else
                return $res;
        }else{
            return $res;
        }
    }

    public function upload_video(){
        $res = $this->handel_upload([
            'fileSize' => config('-upload.video_size') ?? 52428800,
            'fileExt' => config('-upload.video_ext') ?? 'wmv,mpeg,mpg',
            'fileMime' => 'video/mp4,video/x-ms-wmv,video/mpeg',
        ],'admin_video');
        return $res;
    }

    public function upload_audio(){
        $res = $this->handel_upload([
            'fileSize' => config('-upload.audio_size') ?? 10485760,
            'fileExt' => config('-upload.audio_ext') ?? 'mp3,m4a,mav',
            'fileMime' => 'audio/mpeg,audio/wave,audio/x-ms-wma,audio/x-wav,audio/x-m4a',
        ],'admin_audio');
        return $res;
    }

    private function handel_upload(array $rule,string $save_path, bool $site = true)
    {
        //验证码token end
        $result=[];
        $type=input('param.type');
        $files = request()->file();
        foreach($files as $file) {
            $isse=check_illegal($file);
            if(!$isse){
                $result = [
                    'code' => -1,
                    'msg'  => '上传异常'
                ];
                return json($result);exit;
            }
        }
        try {
            validate(['file' => $rule])->check(['file' => $files]);
            //七牛云地址
            $domain=config('-cloudsite.domain');
            if($domain && $site){
                $file=$files['file'];
                // 图片存储在本地的临时路经
                $filePath = $file->getRealPath();
                // 获取图片后缀
                $ext = $file->getOriginalExtension();
                // 上传到七牛后保存的新图片名
                $tim=date('Ymd');
                $newImageName  =   'order/'.$tim.'/'.substr(md5($file->getOriginalName()),0,6)
                    .  rand(00000,99999) . '.'.$ext;
                Qiniu::upload($newImageName,$filePath);
                $domain=config('-cloudsite.domain');
                $result = [
                    'code'     => 0,
                    'msg'      => '上传成功',
                    'img' => $domain.$newImageName,
                    'filename' => $newImageName,
                    'site' => true
                ];
                if($type){
                    $result['filename']=$domain.$newImageName;
                }
            }else{
                $savename = [];
                foreach($files as $file) {
                    $savename[] = \think\facade\Filesystem::disk('public')->putFile( $save_path, $file);
                }
                $img='/storage/'.str_replace('\\','/',$savename[0]);
                $result = [
                    'code'     => 0,
                    'msg'      => '上传成功',
                    'data' => getFullImageUrl($img),
                    'img' => getFullImageUrl($img),
                    'filename' => $img,
                    'site' => false
                ];
                if($type){
                    $result['filename']=getFullImageUrl($img);
                }
            }
        } catch (ValidateException|InvalidArgumentException $e) {
            $result = [
                'code' => -1,
                'msg'  => $e->getMessage()
            ];
        }
        return json($result);
    }
}